package main

import (
	"fmt"
	"io"
	"log"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"time"
)

func main() {
	rs1 := &Srv{addr: "127.0.0.1:2003"}
	rs1.Start()
	rs2 := &Srv{addr: "127.0.0.1:2004"}
	rs2.Start()

	quit := make(chan os.Signal)
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
	<-quit
}

type Srv struct {
	addr string
}

func (s *Srv) Start() {
	fmt.Println("开始监听")
	mux := http.NewServeMux()
	mux.HandleFunc("/", hello)
	mux.HandleFunc("/test/error", errSrv)
	mux.HandleFunc("/test/timeout", timeoutSrv)

	serve := &http.Server{
		Addr:         s.addr,
		WriteTimeout: 3 * time.Second,
		Handler:      mux,
	}

	go func() {
		log.Fatal(serve.ListenAndServe())
	}()

}

func hello(w http.ResponseWriter, r *http.Request) {
	w.Write([]byte(r.URL.Path))
	realIP := fmt.Sprintf("RemoteAddr=%s,X-Forwarded-For=%v,X-Real-Ip=%v\n", r.RemoteAddr, r.Header.Get("X-Forwarded-For"), r.Header.Get("X-Real-Ip"))
	header := fmt.Sprintf("headers =%v\n", r.Header)
	io.WriteString(w, realIP)
	io.WriteString(w, header)
}

func errSrv(w http.ResponseWriter, r *http.Request) {
	w.WriteHeader(http.StatusInternalServerError)
	w.Write([]byte("error"))
}

func timeoutSrv(w http.ResponseWriter, r *http.Request) {
	time.Sleep(6 * time.Second)
	w.WriteHeader(http.StatusOK)
	w.Write([]byte("this is timeout serve"))
}
